package com.rickpan.controller;

import com.rickpan.common.ApiResponse;
import com.rickpan.dto.response.PaymentOrderResponse;
import com.rickpan.dto.response.VipSubscriptionResponse;
import com.rickpan.entity.PaymentOrder;
import com.rickpan.entity.User;
import com.rickpan.entity.VipFeatureConfig;
import com.rickpan.entity.VipSubscription;
import com.rickpan.repository.UserRepository;
import com.rickpan.service.PaymentService;
import com.rickpan.service.VipSubscriptionService;
import com.rickpan.service.VipFeatureService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * VIP管理员控制器
 */
@RestController
@RequestMapping("/api/admin/vip")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "VIP管理后台", description = "VIP系统管理接口")
@PreAuthorize("hasRole('ADMIN')")
public class VipAdminController {

    private final PaymentService paymentService;
    private final VipSubscriptionService subscriptionService;
    private final VipFeatureService featureService;
    private final UserRepository userRepository;

    /**
     * 获取VIP系统总览统计
     */
    @GetMapping("/overview")
    @Operation(summary = "VIP系统总览", description = "获取VIP系统的总体统计信息")
    public ApiResponse<Map<String, Object>> getVipOverview() {
        Map<String, Object> overview = new HashMap<>();
        
        LocalDateTime now = LocalDateTime.now();
        
        // 用户统计
        Long totalVipUsers = userRepository.countVipUsers();
        Long activeVipUsers = userRepository.countActiveVipUsers(now);
        Long basicUsers = userRepository.countBasicUsers();
        
        // 订阅统计
        List<VipSubscription> expiringSubscriptions = subscriptionService.getExpiringSubscriptions();
        
        // 支付统计 (本月)
        LocalDateTime monthStart = now.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        PaymentService.PaymentStatistics monthlyStats = paymentService
            .getPaymentStatistics(monthStart, now);
        
        overview.put("totalVipUsers", totalVipUsers);
        overview.put("activeVipUsers", activeVipUsers);
        overview.put("basicUsers", basicUsers);
        overview.put("expiringSubscriptionsCount", expiringSubscriptions.size());
        overview.put("monthlyOrders", monthlyStats.getTotalOrders());
        overview.put("monthlyRevenue", monthlyStats.getTotalAmount());
        overview.put("monthlyVipCount", monthlyStats.getMonthlyVipCount());
        overview.put("yearlyVipCount", monthlyStats.getYearlyVipCount());
        
        return ApiResponse.success(overview);
    }

    /**
     * 获取所有支付订单 (分页)
     */
    @GetMapping("/orders")
    @Operation(summary = "获取订单列表", description = "分页获取所有支付订单")
    public ApiResponse<List<PaymentOrderResponse>> getAllOrders(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String status) {
        
        // 这里简化实现，实际应该在Repository中添加分页查询方法
        List<PaymentOrder> orders = paymentService.getUserOrders(null); // 获取所有订单
        
        List<PaymentOrderResponse> responses = orders.stream()
            .map(this::convertToPaymentOrderResponse)
            .collect(Collectors.toList());
            
        // 简化的分页处理，实际应该使用数据库分页
        int start = page * size;
        int end = Math.min(start + size, responses.size());
        List<PaymentOrderResponse> pageContent = responses.subList(start, end);
        
        // 返回列表响应
        return ApiResponse.success(pageContent);
    }

    /**
     * 手动确认支付
     */
    @PostMapping("/orders/{orderNo}/confirm")
    @Operation(summary = "手动确认支付", description = "管理员手动确认订单支付状态")
    public ApiResponse<Void> confirmPayment(
            @PathVariable String orderNo,
            @RequestParam String remark) {
        
        paymentService.manualConfirmPayment(orderNo, remark);
        log.info("管理员手动确认支付: orderNo={}, remark={}", orderNo, remark);
        
        return ApiResponse.success();
    }

    /**
     * 获取所有VIP用户
     */
    @GetMapping("/users")
    @Operation(summary = "获取VIP用户列表", description = "获取所有VIP用户信息")
    public ApiResponse<List<Map<String, Object>>> getVipUsers() {
        List<User> vipUsers = userRepository.findAllVipUsers();
        
        List<Map<String, Object>> userInfos = vipUsers.stream()
            .map(this::convertToUserInfo)
            .collect(Collectors.toList());
            
        return ApiResponse.success(userInfos);
    }

    /**
     * 获取所有订阅信息
     */
    @GetMapping("/subscriptions")
    @Operation(summary = "获取订阅列表", description = "获取所有VIP订阅信息")
    public ApiResponse<List<VipSubscriptionResponse>> getAllSubscriptions() {
        // 这里简化实现，实际应该在Service中添加获取所有订阅的方法
        List<User> vipUsers = userRepository.findAllVipUsers();
        
        List<VipSubscriptionResponse> allSubscriptions = vipUsers.stream()
            .flatMap(user -> subscriptionService.getUserSubscriptions(user.getId()).stream())
            .map(this::convertToSubscriptionResponse)
            .collect(Collectors.toList());
            
        return ApiResponse.success(allSubscriptions);
    }

    /**
     * 获取功能配置列表
     */
    @GetMapping("/features")
    @Operation(summary = "获取功能配置", description = "获取所有VIP功能配置")
    public ApiResponse<List<VipFeatureConfig>> getFeatureConfigs() {
        List<VipFeatureConfig> configs = featureService.getAllFeatureConfigs();
        return ApiResponse.success(configs);
    }

    /**
     * 手动为用户开通VIP
     */
    @PostMapping("/users/{userId}/grant-vip")
    @Operation(summary = "手动开通VIP", description = "管理员为指定用户手动开通VIP")
    public ApiResponse<Void> grantVipToUser(
            @PathVariable Long userId,
            @RequestParam String planType,
            @RequestParam String remark) {
        
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
            
        // 创建手动订单
        PaymentOrder.PlanType plan = PaymentOrder.PlanType.valueOf(planType);
        PaymentOrder order = paymentService.createPaymentOrder(userId, plan);
        
        // 手动确认支付
        paymentService.manualConfirmPayment(order.getOrderNo(), "管理员手动开通: " + remark);
        
        log.info("管理员为用户 {} 手动开通VIP: planType={}, remark={}", 
                user.getUsername(), planType, remark);
        
        return ApiResponse.success();
    }

    /**
     * 获取支付统计信息
     */
    @GetMapping("/statistics/payment")
    @Operation(summary = "支付统计", description = "获取指定时间范围的支付统计信息")
    public ApiResponse<PaymentService.PaymentStatistics> getPaymentStatistics(
            @RequestParam String startTime,
            @RequestParam String endTime) {
        
        LocalDateTime start = LocalDateTime.parse(startTime);
        LocalDateTime end = LocalDateTime.parse(endTime);
        
        PaymentService.PaymentStatistics stats = paymentService.getPaymentStatistics(start, end);
        return ApiResponse.success(stats);
    }

    /**
     * 转换支付订单为响应对象
     */
    private PaymentOrderResponse convertToPaymentOrderResponse(PaymentOrder order) {
        return PaymentOrderResponse.builder()
            .id(order.getId())
            .orderNo(order.getOrderNo())
            .planType(order.getPlanType().name())
            .amount(order.getAmount())
            .status(order.getStatus().name())
            .paymentMethod(order.getPaymentMethod().name())
            .createdAt(order.getCreatedAt())
            .paidAt(order.getPaidAt())
            .expiresAt(order.getExpiresAt())
            .remark(order.getRemark())
            .build();
    }

    /**
     * 转换订阅为响应对象
     */
    private VipSubscriptionResponse convertToSubscriptionResponse(VipSubscription subscription) {
        Long daysLeft = ChronoUnit.DAYS.between(LocalDateTime.now(), 
            subscription.getEndDate().atStartOfDay());
        if (daysLeft < 0) daysLeft = 0L;

        String planName = subscription.getPlanType() == PaymentOrder.PlanType.MONTHLY_VIP 
            ? "月度VIP" : "年度VIP";

        return VipSubscriptionResponse.builder()
            .id(subscription.getId())
            .userId(subscription.getUserId())
            .orderId(subscription.getOrderId())
            .planType(subscription.getPlanType().name())
            .planName(planName)
            .startDate(subscription.getStartDate())
            .endDate(subscription.getEndDate())
            .status(subscription.getStatus().name())
            .statusDescription(subscription.getStatus().getDescription())
            .autoRenew(subscription.getAutoRenew())
            .originalAmount(subscription.getOriginalAmount())
            .discountAmount(subscription.getDiscountAmount())
            .actualAmount(subscription.getActualAmount())
            .createdAt(subscription.getCreatedAt())
            .daysLeft(daysLeft)
            .build();
    }

    /**
     * 转换用户信息
     */
    private Map<String, Object> convertToUserInfo(User user) {
        Map<String, Object> info = new HashMap<>();
        info.put("id", user.getId());
        info.put("username", user.getUsername());
        info.put("email", user.getEmail());
        info.put("realName", user.getRealName());
        info.put("userType", user.getUserType().name());
        info.put("vipExpireTime", user.getVipExpireTime());
        info.put("storageQuota", user.getStorageQuota());
        info.put("storageUsed", user.getStorageUsed());
        info.put("createdAt", user.getCreatedAt());
        
        if (user.getVipExpireTime() != null) {
            long daysLeft = ChronoUnit.DAYS.between(LocalDateTime.now(), user.getVipExpireTime());
            info.put("daysLeft", Math.max(0, daysLeft));
        }
        
        return info;
    }
}